package com.hixtrip.sample.infra;

import com.hixtrip.sample.domain.inventory.model.Inventory;
import com.hixtrip.sample.domain.inventory.repository.InventoryRepository;
import com.hixtrip.sample.infra.constant.RedisKeyConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * infra层是domain定义的接口具体的实现
 */
@Component
public class InventoryRepositoryImpl implements InventoryRepository {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    /**
     * 获取库存
     */
    @Override
    public Inventory getInventory(String skuId) {

        String redisKey = RedisKeyConstant.INVENTORY_KEY + skuId;

        Long quantity = 0L;
        Long occupied = 0L;

        Map<Object, Object> objectMap = redisTemplate.boundHashOps(redisKey).entries();

        // --------------- 测试代码,初始化数据 begin ------------------
        if (objectMap == null || objectMap.size() == 0){
            this.changeInventory(skuId, 10000L, 0L);
            objectMap = redisTemplate.boundHashOps(redisKey).entries();
        }
        // --------------- 测试代码,初始化数据 end ------------------

        if (objectMap != null){
            quantity = Long.valueOf((Integer) objectMap.get(RedisKeyConstant.INVENTORY_SELLABLE_KEY));
            occupied = Long.valueOf((Integer) objectMap.get(RedisKeyConstant.INVENTORY_OCCUPIED_KEY));
        }

        return Inventory.builder()
                .sellableQuantity(quantity)
                .occupiedQuantity(occupied)
                .build();
    }


    /**
     * 扣减库存
     * @param newSellableQuantity 可售库存
     * @param newOccupiedQuantity 占用库存
     */
    @Override
    public void changeInventory(String skuId, long newSellableQuantity, long newOccupiedQuantity) {
        String redisKey = RedisKeyConstant.INVENTORY_KEY + skuId;
        HashMap<String, Object> data = new HashMap<>();
        data.put(RedisKeyConstant.INVENTORY_SELLABLE_KEY, newSellableQuantity);
        data.put(RedisKeyConstant.INVENTORY_OCCUPIED_KEY, newOccupiedQuantity);
        redisTemplate.boundHashOps(redisKey).putAll(data);
    }
}
